﻿//#define ID_AUTO_INCREMENT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Sonce.Database
{
	public class Table<T> : IEnumerable<T>, IEnumerable where T : ITable
	{
		#region Members
		private List<T> list = new List<T>();
		private bool autoIncrement = true;
		private string tableName = null;
		#endregion

		#region Constructor
		public Table()
		{
		}
		#endregion

		#region Properties
		public bool AutoIncrement
		{
			get
			{
				return this.autoIncrement;
			}
			set
			{
				this.autoIncrement = value;
			}
		}

		public string TableName
		{
			get
			{
				return this.tableName;
			}
			set
			{
				this.tableName = value;
			}
		}
		#endregion

		#region Methods
		public void Insert(T item)
		{
#if ID_AUTO_INCREMENT
            if (this.AutoIncrement)
            {
                int id = 1;
                if (list.Count > 0)
                {
                    //Get next ID
                    id = list[list.Count - 1].ID + 1;

                    //TODO: More reliable would be to search for the highest ID and then increase by one
                }
                item.ID = id;
            }
            //else //Temporarily commented while testing inserts with AutoIncrement
            {
                //Avoid ID collision
                int existing =
                   (from i in list
                    where i.ID == item.ID
                    select i).Count();

                if (existing > 0)
                {
                    throw new Exception("A row with the same ID already exists in the table.");
                }
            }
#endif
			list.Add(item);
		}

		public void Delete(T item)
		{
			list.Remove(item);
		}

		public void Import(List<T> items)
		{
			//No checking for IDs
			foreach (T item in items)
			{
				list.Add(item);
			}
		}

		public List<T> Export()
		{
			return list;
		}
		#endregion

		#region IEnumerable<T> Members
		public IEnumerator<T> GetEnumerator()
		{
			return list.GetEnumerator();
		}
		#endregion

		#region IEnumerable Members
		IEnumerator IEnumerable.GetEnumerator()
		{
			return list.GetEnumerator();
		}
		#endregion
	}
}
